import React, { useState, useEffect, useRef } from 'react';
import styled from 'styled-components';
import { motion, AnimatePresence } from 'framer-motion';
import { useAuth } from '../contexts/AuthContext';
import { logInfo, logError } from '../logger';
import { colors, spacing, typography } from '../styles/variables';
import { Card, Title, Button, Input, Flex } from '../styles/components';
import Modal from './Modal';
import { uploadAvatar } from '../services/uploadService';

const Form = styled.form`
  display: flex;
  flex-direction: column;
  gap: ${spacing.lg};
  width: 100%;
`;

const FormGroup = styled.div`
  display: flex;
  flex-direction: column;
  gap: ${spacing.sm};
`;

const Label = styled.label`
  font-size: ${typography.fontSize.sm};
  font-weight: ${typography.fontWeight.medium};
  color: ${colors.textPrimary};
`;

const ErrorMessage = styled.div`
  color: ${colors.error};
  font-size: ${typography.fontSize.sm};
  margin-top: ${spacing.sm};
`;

const EditProfileModal = ({ isOpen, onClose }) => {
  const { user, updateProfile } = useAuth();
  const [formData, setFormData] = useState({
    username: '',
    avatarUrl: '',
    birthDate: '',
    birthTime: '',
    timezone: ''
  });
  const [loading, setLoading] = useState(false);
  const [error, setError] = useState('');
  const [avatarPreview, setAvatarPreview] = useState('');
  const fileInputRef = useRef(null);

  // 初始化表单数据
  useEffect(() => {
    if (user && isOpen) {
      setFormData({
        username: user.username || '',
        avatarUrl: user.avatarUrl || '',
        birthDate: user.birthDate || '',
        birthTime: user.birthTime || '',
        timezone: user.timezone || ''
      });
      setAvatarPreview(user.avatarUrl || '');
      setError('');
    }
  }, [user, isOpen]);

  // 处理输入变化
  const handleChange = (e) => {
    const { name, value } = e.target;
    setFormData(prev => ({
      ...prev,
      [name]: value
    }));
  };

  /**
   * 处理文件选择
   * @param {Event} e - 文件选择事件
   */
  const handleFileSelect = (e) => {
    const file = e.target.files[0];
    if (file) {
      // 验证文件类型
      if (!file.type.startsWith('image/')) {
        setError('请选择有效的图片文件');
        return;
      }
      
      // 验证文件大小 (最大5MB)
      if (file.size > 5 * 1024 * 1024) {
        setError('文件大小不能超过5MB');
        return;
      }
      
      // 设置预览
      const reader = new FileReader();
      reader.onload = (e) => {
        setAvatarPreview(e.target.result);
      };
      reader.readAsDataURL(file);
      
      // 清除之前的错误信息
      setError('');
    }
  };

  /**
   * 触发文件选择对话框
   */
  const triggerFileSelect = () => {
    fileInputRef.current.click();
  };

  // 处理表单提交
  const handleSubmit = async (e) => {
    e.preventDefault();
    setLoading(true);
    setError('');

    try {
      // 如果用户选择了新头像，则先上传头像
      if (fileInputRef.current.files.length > 0) {
        const file = fileInputRef.current.files[0];
        // 验证是否为图片文件
        if (file.type.startsWith('image/')) {
          // 上传头像
          const uploadResult = await uploadAvatar(file);
          
          // 更新表单数据中的头像URL
          setFormData(prev => ({
            ...prev,
            avatarUrl: uploadResult.url
          }));
          
          // 使用上传后的URL更新用户资料
          await updateProfile({
            ...formData,
            avatarUrl: uploadResult.url
          });
        } else {
          // 如果不是有效图片，使用原来的avatarUrl
          await updateProfile(formData);
        }
      } else {
        // 没有新头像，直接更新资料
        await updateProfile(formData);
      }
      
      logInfo('用户资料更新成功', { userId: user.id });
      
      // 调用成功回调
      if (onSuccess) {
        onSuccess();
      }
      
      // 关闭模态框
      onClose();
    } catch (err) {
      logError('用户资料更新失败', { error: err.message });
      setError(err.message || '更新失败，请稍后重试');
    } finally {
      setLoading(false);
    }
  };

  // 处理模态框关闭
  const handleClose = () => {
    setError('');
    onClose();
  };

  // 隐藏的文件输入框
  const hiddenFileInput = {
    position: 'absolute',
    left: '-9999px',
    top: '-9999px'
  };

  return (
    <AnimatePresence>
      {isOpen && (
        <Modal isOpen={isOpen} onClose={handleClose}>
          <motion.div
            initial={{ opacity: 0, y: -20 }}
            animate={{ opacity: 1, y: 0 }}
            exit={{ opacity: 0, y: -20 }}
            transition={{ duration: 0.3 }}
          >
            <Card style={{ width: '100%', maxWidth: '500px', margin: '0 auto' }}>
              <Title size="md" style={{ textAlign: 'center', marginBottom: spacing.xl }}>
                编辑资料
              </Title>
              
              <Form onSubmit={handleSubmit}>
                <FormGroup>
                  <Label htmlFor="username">用户名</Label>
                  <Input
                    id="username"
                    name="username"
                    type="text"
                    value={formData.username}
                    onChange={handleChange}
                    placeholder="请输入用户名"
                  />
                </FormGroup>
                
                <FormGroup>
                  <Label>头像</Label>
                  <div style={{ display: 'flex', alignItems: 'center', gap: '16px' }}>
                    {/* 头像预览 */}
                    <div 
                      style={{ 
                        width: '64px', 
                        height: '64px', 
                        borderRadius: '50%', 
                        overflow: 'hidden',
                        border: `2px solid ${colors.border}`,
                        display: 'flex',
                        alignItems: 'center',
                        justifyContent: 'center'
                      }}
                    >
                      {avatarPreview ? (
                        <img 
                          src={avatarPreview} 
                          alt="头像预览" 
                          style={{ width: '100%', height: '100%', objectFit: 'cover' }}
                        />
                      ) : (
                        <div style={{ color: colors.textSecondary, fontSize: '24px' }}>👤</div>
                      )}
                    </div>
                    
                    {/* 上传按钮 */}
                    <div>
                      <Button 
                        type="button" 
                        onClick={triggerFileSelect}
                        variant="secondary"
                        style={{ marginRight: '8px' }}
                      >
                        选择图片
                      </Button>
                      <span style={{ color: colors.textSecondary, fontSize: '14px' }}>
                        {fileInputRef.current?.files[0] ? fileInputRef.current.files[0].name : '未选择文件'}
                      </span>
                    </div>
                    
                    {/* 隐藏的文件输入框 */}
                    <input
                      type="file"
                      ref={fileInputRef}
                      onChange={handleFileSelect}
                      accept="image/*"
                      style={hiddenFileInput}
                    />
                  </div>
                  
                  {/* 保留原来的头像URL输入框，但隐藏 */}
                  <Input
                    id="avatarUrl"
                    name="avatarUrl"
                    type="text"
                    value={formData.avatarUrl}
                    onChange={handleChange}
                    placeholder="请输入头像URL"
                    style={{ display: 'none' }}
                  />
                </FormGroup>
                
                <Flex gap={spacing.md}>
                  <FormGroup style={{ flex: 1 }}>
                    <Label htmlFor="birthDate">出生日期</Label>
                    <Input
                      id="birthDate"
                      name="birthDate"
                      type="date"
                      value={formData.birthDate}
                      onChange={handleChange}
                    />
                  </FormGroup>
                  
                  <FormGroup style={{ flex: 1 }}>
                    <Label htmlFor="birthTime">出生时间</Label>
                    <Input
                      id="birthTime"
                      name="birthTime"
                      type="time"
                      value={formData.birthTime}
                      onChange={handleChange}
                    />
                  </FormGroup>
                </Flex>
                
                <FormGroup>
                  <Label htmlFor="timezone">时区</Label>
                  <Input
                    id="timezone"
                    name="timezone"
                    type="text"
                    value={formData.timezone}
                    onChange={handleChange}
                    placeholder="例如: Asia/Shanghai"
                  />
                </FormGroup>
                
                {error && <ErrorMessage>{error}</ErrorMessage>}
                
                <Flex gap={spacing.md} style={{ marginTop: spacing.lg }}>
                  <Button 
                    type="button" 
                    variant="outline" 
                    onClick={handleClose}
                    style={{ flex: 1 }}
                    disabled={loading}
                  >
                    取消
                  </Button>
                  <Button 
                    type="submit" 
                    variant="primary" 
                    style={{ flex: 1 }}
                    disabled={loading}
                  >
                    {loading ? '保存中...' : '保存'}
                  </Button>
                </Flex>
              </Form>
            </Card>
          </motion.div>
        </Modal>
      )}
    </AnimatePresence>
  );
};

export default EditProfileModal;